package com.wits100.av;

import android.util.Log;

/**
 * Created by zhengboyuan on 2017-02-11.
 */

public class TimestampCounter {

    public static final String TAG = "player";

    public static final long MIN_CLOCK_DURATION = 1000;
    public static final long DISCONTINUITY_SCALE = 5;

    public static final long MAX_PTS_DELTA = 500;


    public TimestampCounter() {

    }

    public long getDuration() {
        return duration;
    }

    public long getDelta(long pts) {
        long delta = 0;

        if (pts < 0) {
            //Log.w(TAG, "bad pts: " + pts);
            reset();
            return 0;
        }

        TimePoint pt = new TimePoint(pts, System.currentTimeMillis());

        if (startPoint == null) {
            Log.i("test", "start pt: " + pt);

            startPoint = new TimePoint(pt.pts, pt.clock);
            prevPoint = pt;
            count ++;

            delta = 0;
        } else {
            count ++;

            long ptsDelta = pt.pts - prevPoint.pts;
            long clockDelta = pt.clock - prevPoint.clock;

            long clockDuration = pt.clock - startPoint.clock;
            if (clockDuration > MIN_CLOCK_DURATION) {
                duration = clockDuration / count;
            }

            boolean shouldReset = false;

            if (ptsDelta < 0) {
                shouldReset = true;
            } else if (ptsDelta > MAX_PTS_DELTA) {
                Log.w(TAG, "too big ptsDelta: " + ptsDelta);
                shouldReset = true;
            } else {
                if (duration > 0 && (ptsDelta > (DISCONTINUITY_SCALE * duration))) {
                    shouldReset = true;
                }
            }

            if (shouldReset) {
                Log.w(TAG, "discontinuity checked. pts: " + pts + " ptsDelta: " + ptsDelta + " clockDelta: " + clockDelta);
                Log.w(TAG, " duration: " + duration + " count: " + count + " start: " + startPoint + " prev: " + prevPoint);

                reset();
            } else {
                delta = pt.delta(startPoint);

                prevPoint = pt;
            }

        }

//        if (count % 30 == 1) {
//            Log.i("test", "pts: " + pts + " clock: " + pt.clock + " delta: " + delta);
//        }

        return delta;
    }

    public void reset() {

        startPoint = null;

        prevPoint.reset();
        duration = 0;
    }

    protected long duration;

    protected TimePoint startPoint;
    protected TimePoint prevPoint = new TimePoint();
    protected long count;

}
